//
//  simMessageViewController.m
//  simens
//
//  Created by xx xx on 12-7-17.
//  Copyright (c) 2012年 yst. All rights reserved.
//

#import "simMessageViewController.h"
#import "simMessageDetailViewController.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "simModifyPasswdViewController.h"
#import "simShopVisitScheduleController.h"


@implementation Message

@synthesize mid,mobile,smscontent,smstype,sendtime,result,state,title;


@end


@interface simMessageViewController ()<ASIHTTPRequestDelegate>
@property (nonatomic,strong) UITableView *messageTableView;
@property (nonatomic,strong) UITableView *teamTableView;


@end

@implementation simMessageViewController
@synthesize dataList;
@synthesize messageTableView = _messageTableView;
@synthesize teamTableView = _teamTableView;



NSMutableArray* messageItemArray;
NSMutableArray* sendMessageItemArray;
NSArray* reportArray;
NSArray* tableViewArray;
ASIHTTPRequest* initRequest;
ASIHTTPRequest* countRequest;
NSString* totalCount;
NSString* planCount;
//int proportion;
bool vistType;
NSString* jdu;
NSString* name;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
            }
    return self;
}

- (void)viewDidLoad
{
    
    
    self.title=@"我的中心"; 
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.messageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                                          self.view.bounds.size.height - 150)
                                                         style:UITableViewStylePlain];  
    
    [self.messageTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.messageTableView setDelegate:self];
    [self.messageTableView setDataSource:self];
    [self.view addSubview: self.messageTableView];
    
    
    self.teamTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 306, self.view.bounds.size.width,
                                                                          self.view.bounds.size.height - 80)
                                                         style:UITableViewStylePlain];
    
    [self.teamTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.teamTableView setDelegate:self];
    [self.teamTableView setDataSource:self];
    [self.view addSubview: self.teamTableView];
    

    
    /*
    messageItemArray = [[NSMutableArray alloc] init];
    
    for (int i=0; i<10; i++) {
        
        Message* message = [[Message alloc] init];
    
            message.sms_id = [@"2012-07-2" stringByAppendingString:[NSString stringWithFormat:@"%d", i]];
            message.smscontent = [@"决议" stringByAppendingString:[NSString stringWithFormat:@"%d",  i]];
        
                
        [messageItemArray addObject:message]; 
    }
    //sendMessageItemArray = [[NSMutableArray alloc] initWithArray:messageItemArray];
    //self.dataList = messageItemArray;
    */
    /*
    UIBarButtonItem* tempRight = [[UIBarButtonItem alloc] initWithTitle:@"密码修改" style:UIBarButtonItemStylePlain target:self action:@selector(modifyPasswd)];

    self.navigationItem.rightBarButtonItem = tempRight;
    */
   
    UIBarButtonItem* te = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCompose target:self action:@selector(modifyPasswd)];
    self.navigationItem.rightBarButtonItem = te;
    
        [super viewDidLoad];
	// Do any additional setup after loading the view.
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self showMbprogress];
    NSString *u =[NSString stringWithFormat:@"%@/getSendWaitMess?mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    NSURL *url = [NSURL URLWithString: u];
    
    initRequest = [ASIHTTPRequest requestWithURL:url];
    [initRequest setDelegate:self];
    [initRequest start];
    
    NSString *u1 =[NSString stringWithFormat:@"%@/getVistCustNum?mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    NSURL *url1 = [NSURL URLWithString: u1];
    
    countRequest = [ASIHTTPRequest requestWithURL:url1];
    [countRequest setDelegate:self];
    [countRequest start];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if(tableView==self.messageTableView){
        return 2;
    }else if(tableView==self.teamTableView){
        return 1;
    }
    return 1;
}// Default is 1 if not implemented



//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView==self.messageTableView){
        if (section == 1) {
            return [messageItemArray count];
        }else if (section == 0) {
            
            return 1;
        }

    }else if(tableView == self.teamTableView){
        return 1;
    }
        
    
    return 1;

    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    } 
    
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UIImage class]] |
            [v isKindOfClass:[UIImageView class]]|
            [v isKindOfClass:[UIProgressView class]]) {
            [v removeFromSuperview];
        }
    }
    
    
    [cell.textLabel setBackgroundColor:[UIColor clearColor]];
    

    CGFloat x1;
    CGFloat x2;
    if(vistType) {
        x1 = 20;
        x2 = 160;
    } else{
        x1 = 20;
        x2 = 140;
    }
    
    
    if(tableView==self.messageTableView){
    
        if(indexPath.section==0){
            
            
            UIProgressView* progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 10, 280, 30)];
            [progressView setProgressViewStyle:UIProgressViewStyleDefault];
            
            if ([totalCount floatValue] == 0.00f) {
                progressView.progress = 0.00f;
            } else {
                progressView.progress = [planCount floatValue] / [totalCount floatValue];
            }
            
            if(progressView.progress<0.6){
                [progressView setProgressTintColor:[UIColor redColor]];
            }else {
                [progressView setProgressTintColor:[UIColor greenColor]];
            }
            
            [cell addSubview:progressView];
            
            
        }else if(indexPath.section==1){
            
            Message* message;
            
            if ([messageItemArray count] != 0) {
                message = [messageItemArray objectAtIndex:indexPath.row];
            }
            
            NSString *sendtime = message.sendtime;
            NSString *time = [sendtime substringFromIndex:10];
            NSString *date = [sendtime substringToIndex:10];
            
            
            NSString *state = message.state;
            NSString *tempState=@"";
            if([state isEqualToString:@"Y"]){
                tempState=@"已读";
            }else{
                tempState=@"未读";
            }
            
            UILabel* sendDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(x1, 0, 100, 40)];
            [sendDateLabel setBackgroundColor:[UIColor clearColor]];
            [sendDateLabel setText:date];
            sendDateLabel.font=[UIFont systemFontOfSize:18];
            //sendDateLabel.textAlignment = UITextAlignmentCenter;
            [cell addSubview:sendDateLabel];
            
            UILabel* sendTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(x1, 25, 100, 40)];
            [sendTimeLabel setBackgroundColor:[UIColor clearColor]];
            [sendTimeLabel setText:time];
            sendTimeLabel.font=[UIFont systemFontOfSize:16];
            //sendTimeLabel.textAlignment = UITextAlignmentCenter;
            [cell addSubview:sendTimeLabel];
            
            
            UILabel* stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(x2, 5, 160, 30)];
            [stateLabel setBackgroundColor:[UIColor clearColor]];
            [stateLabel setText:[NSString stringWithFormat:@"状态：%@", tempState]];
            if([state isEqualToString:@"Y"]){
                [stateLabel setTextColor:[UIColor blueColor]];
            }else {
                [stateLabel setTextColor:[UIColor redColor]];
            }
            
            
            stateLabel.font=[UIFont systemFontOfSize:12];
            [cell addSubview:stateLabel];
            UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(x2, 30, 160, 30)];
            [contentLabel setBackgroundColor:[UIColor clearColor]];
            [contentLabel setText:[NSString stringWithFormat:@"%@",message.title]];
            [contentLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
            contentLabel.font=[UIFont systemFontOfSize:12];
            [cell addSubview:contentLabel];
        }
    
                
        /*
         NSString *content = message.smscontent;
         NSString *count = [NSString stringWithFormat:@"%d:", indexPath.row+1] ;
         NSString *laberStr = [count stringByAppendingString:content ];
         [cell.textLabel setText:laberStr];
         cell.textLabel.font=[UIFont systemFontOfSize:18];
         */
        
    }else if(tableView == self.teamTableView){
            cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
            
            UILabel* nameLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 0, 150, 40)];
            [nameLabel setBackgroundColor:[UIColor clearColor]];
            [nameLabel setText:@"拜访进度查询"];
            nameLabel.font=[UIFont systemFontOfSize:16];
            [cell addSubview:nameLabel];
            
            UILabel* valueLabel =[[UILabel alloc] initWithFrame:CGRectMake(90, 5, 200, 40)];
            [valueLabel setBackgroundColor:[UIColor clearColor]];
            valueLabel.font=[UIFont systemFontOfSize:16];
            valueLabel.textAlignment = UITextAlignmentRight;
            [cell addSubview:valueLabel];
        
    }

    UIImage* seletedImg = [UIImage imageNamed:@"tableviewcellSelected.png"];
    UIImageView *seletedImgView =[[UIImageView alloc] initWithImage:seletedImg];
    [cell setSelectedBackgroundView:seletedImgView];
    
    UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];
    UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
    [cell setBackgroundView:backImgView];

    return cell;
    
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView==self.messageTableView){
        if (indexPath.section==0) {
            return 30;
        }else if(indexPath.section==1){
            return 56.5;
        }
    }else if(tableView==self.teamTableView){
        if (indexPath.section==0) {
            return 40;
        }
    }
    
    
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 30;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(tableView==self.messageTableView){
        if (indexPath.section==1) {            
            NSUInteger row = [indexPath row];
            Message* message = [messageItemArray objectAtIndex:row];
            
            //[self.navigationController popViewControllerAnimated:YES];
            simMessageDetailViewController* messageDetailController = [[simMessageDetailViewController alloc] init];
            [messageDetailController setItems:message];     //[messageController setHidesBottomBarWhenPushed:NO];
            [self.navigationController pushViewController:messageDetailController animated:YES];
            
        }
    }else if(tableView==self.teamTableView){
        simShopVisitScheduleController *controller=[[simShopVisitScheduleController alloc] init];
        [controller setTitles:@"我的团队"];
        // set posId
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"posId"];
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"t"];
        [self.navigationController pushViewController:controller animated:YES];
    }
    
    
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if(tableView==self.messageTableView){
        if(section==0){
            NSString *temptot = @"";
            if ([totalCount floatValue] == 0.00f) {
                temptot = @"0";
            }else{
                temptot = [NSString stringWithFormat:@"%@", totalCount];
            }
            
            NSString *tempplan = @"";
            if ([planCount floatValue] == 0.00f) {
                tempplan = @"0";
            }else{
                tempplan = [NSString stringWithFormat:@"%@", planCount];
            }
            
            
            NSMutableString *ms = [[NSMutableString alloc] init];
            [ms appendString: tempplan];
            [ms appendFormat:@"/"];
            [ms appendString: temptot];
            
            return [NSString stringWithFormat:@"%@%@", @"计划拜访进度：                      ", ms];
        }else if (section == 1) {
            return @"我的消息：";
        }
    }else if(tableView == self.teamTableView){
        return @"我的团队：";
    }
    
    return @"";
       
}



- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    if(request==initRequest){
        if (!error) {
            [self showMbprogress];
            NSString *response = [request responseString];
            NSLog(@"%@@=========",response);
            NSDictionary* dict = [response objectFromJSONString];
            reportArray = [dict objectForKey:@"sendWait"];
            tableViewArray = reportArray;
            messageItemArray = [[NSMutableArray alloc] init];
            if(reportArray != nil){
                for (int i = 0; i < reportArray.count; i++) {
                    Message* message = [[Message alloc] init];
                    NSDictionary* temp = [reportArray objectAtIndex:i];
                    
                    //message.mid = [NSString stringWithFormat:@"%d",[temp objectForKey:@"id"]];
                    message.mid = [[temp objectForKey:@"id"] stringValue];
                    message.sendtime = [temp objectForKey:@"sendtime"];
                    message.smscontent =[NSString stringWithFormat:@"%@",[temp objectForKey:@"smscontent"]];
                    message.mobile = [[temp objectForKey:@"mobile"] stringValue];
                    message.smstype = [temp objectForKey:@"smstype"];
                    message.state = [temp objectForKey:@"status"];
                    message.title = [NSString stringWithFormat:@"%@",[temp objectForKey:@"title"] == nil ? @"" : [temp objectForKey:@"title"]];
                    
                    [messageItemArray addObject:message];
                }

            }
            
            [self hideMbProgress];
            [self.messageTableView reloadData];
            
        }


    }
    if(request==countRequest){
        if (!error) {
            NSString *response = [request responseString];
            NSLog(@"%@@=========",response);
            [self showMbprogress];
            if(response!=nil){
                NSArray *aArray = [response componentsSeparatedByString:@","];
                totalCount = [aArray objectAtIndex:0];
                planCount = [aArray objectAtIndex:1];
            }
            //proportion = (totalCount-planCount);
            [self hideMbProgress];
            [self.messageTableView reloadData];
        }
    }
}


- (void)requestFailed:(ASIHTTPRequest *)request {
     [self hideMbProgress];
}

- (void)modifyPasswd {
    simModifyPasswdViewController * modifyPasswdController = [[simModifyPasswdViewController alloc] init];
    [self.navigationController pushViewController:modifyPasswdController animated:YES];
}


@end
